<?php
function _expDESC($a, $b) {
	if($a['exp'] == $b['exp']) {
		return 0;
	}
	return $a['exp'] > $b['exp'] ? -1 : 1;
}
function _expASC($a, $b) {
	if($a['exp'] == $b['exp']) {
		return 0;
	}
	return $a['exp'] < $b['exp'] ? -1 : 1;
}
function _scoreDESC($a, $b) {
	if($a['score'] == $b['score']) {
		return 0;
	}
	return $a['score'] > $b['score'] ? -1 : 1;
}
function _scoreASC($a, $b) {
	if($a['score'] == $b['score']) {
		return 0;
	}
	return $a['score'] < $b['score'] ? -1 : 1;
}

class User extends TagsAbstract {
	/**
	 * 是否是封闭的标签
	 * @var unknown_type
	 */
	static $TAG_CLOSED = false;

	public $config = array();

	public function __construct(){

	}
	public function getTagStatus(){
		return self::$TAG_CLOSED;
	}
	/**
	 * 返回模板文件路径
	 */
	public function getTemplateFile($tpl = "") {
		//返回需要渲染的模板
		$file = $this->attr ['style'];
		if(!empty($tpl)){
			$file = $tpl;
		}
		return dirname(__FILE__).'/user/'.$file.'.html';
	}

	/**
	 * 设置使用哪个Widget,暂时无用。。
	 */
	public function setWidget() {
		return 'test';
	}

	/**
	 * 这里返回的是模板中需要渲染的变量
	 */
	public function replace($checkCache) {
		$order  = isset($this->attr['order']) ? $this->attr['order']		 : 'uid ASC';
		$limit  = isset($this->attr['limit']) ? intval($this->attr['limit']) : 20;
		$status = $this->attr['status'];
		!isset($this->attr['words']) && $this->attr['words'] = 10;

		$source = $this->attr['source'];
		//根据数据源获取总的用户ID集
		$ids = array();

		//将排序组装成方法
		$orderSplit = explode(' ',$order);
		$method = $orderSplit[0];
		$sort   = $orderSplit[1];

		//查处所有符合条件的并排序后的用户
		if($method === 'exp' || $method === 'score'){
			$res = $this->sourceOrder($source,$order,$limit,$method);
		}else{
			$res = $this->$method($source,$sort,$limit);
		}
		//填充部门信息、金币数和贡献值信息
		$ids = $this->_format($res,'uid');
		$sqlDep =  'SELECT  users.uid,users.uname,users.fullname,userInfo.value as \'dept\'
				 	FROM `'.C('DB_PREFIX').'user` as  users   LEFT JOIN  `'.C('DB_PREFIX').'space_search` as  userInfo
				 	ON (userInfo.uid = users.uid)
					where users.uid IN ( ' . implode(',', $ids) . ' ) AND userInfo.info = "department" AND type = "baseinfo"';

		
		$tempUserInfo  = M('')->query($sqlDep);
		$temp = array();
		foreach($tempUserInfo as $key=>$value){
			$temp[$value['uid']] = $key;
		}
		foreach($res as &$value){
			$tempUserInfo[$temp[$value['uid']]]['uname'] = $tempUserInfo[$temp[$value['uid']]]['fullname'];
			$value = array_merge($value,$tempUserInfo[$temp[$value['uid']]]);
		}
		//根据status填充信息（3:最新动态 4:最新记录 5:最新问题 6:最新帖子 7:最新博文 8:最新词条）

		$res = $this->_fillByStatus($res, $status, 5);
		//For mid_top2.html（模板中列出前两篇XX）
		$last_x = array();
		if($status == 3) {
			$last_x['type']  = 'feed';
		}else if($status == 4) {
			$last_x['type']  = 'record';
		}else if($status == 5) {
			$last_x['type']  = 'ask';
		}else if($status == 6) {
			$last_x['type']  = 'bbs';
		}else if($status == 7) {
			$last_x['type']  = 'blog';
		}else if($status == 8) {
			$last_x['type']  = 'wiki';
		}else if($status == 1){
			$last_x['type'] = 'followed';
		}else if($status == 2){
			$last_x['type'] = 'score';
		}
		$var['last_x'] = $last_x;
		$var['title'] = t($this->attr['title']);
		$var['list']  = $res;
		$var['attr']  = $this->attr;
		return $var;
	}
	private function uid($source,$order,$limit){
		$sqlQuery['order'] = 'uid '.$order;
		$sqlQuery['table'] = '`ts_user` as users';
		$sqlQuery['field'] = 'users.uname,users.fullname';
		$sqlQuery['on']    = 'users.uid';
		switch($source){
			case 'group' :
				$where  = $this->attr['group'] == 'ALL' ? '' : 'WHERE ugroup.gid = '.$this->attr['group'];
				$idsSql = 'SELECT distinct(ugroup.uid),'.$sqlQuery['field'].'
						   FROM `ts_user_group` as ugroup  
						   LEFT JOIN '.$sqlQuery['table'].'
						   ON ('.$sqlQuery['on'].'= ugroup.uid) 
						   '.$where.' 
						   ORDER BY '.$sqlQuery['order'].'
						   limit 0,'.$limit;
				$res = M('')->query($idsSql);
				break;
			case 'user'  :
				$ids = $this->getNeedUserInfo();
				$map['uid'] = array('in',$ids);
				$res = M('user')->field('uname,uid,fullname')->where($map)->order($sqlQuery['order'])->limit($limit)->findAll();
				break;
			default:
				$map['active'] = 1;
				$res = M('user')->field('uname,uid,fullname')->where($map)->order($sqlQuery['order'])->limit($limit)->findAll();
		}
		return $res;
	}

	private function followed($source,$order,$limit){
		switch($source){
			case 'group' :
				if($this->attr['group'] !== 'ALL'){
					$map['gid'] = $this->attr['group'];
				}
				$groupUser = M('UserGroup')->where($map)->field('uid')->findAll();
				$uid = $this->_format($groupUser,'uid');
				$uid = array_unique($uid);
				$sql = 'SELECT count(follow.aimId) as counts ,follow.aimId as uid,users.uname,users.fullname
						FROM `ts_follow` as follow 
						LEFT JOIN `ts_user` as users
						ON follow.aimId = users.uid
						WHERE follow.aimId IN ( ' . implode(',', $uid) . ' ) AND follow.type = \'user\'
						GROUP BY follow.aimId
						ORDER BY counts '.$order.'
						LIMIT 0,'.$limit;
				break;
			case 'user'  :
				$ids = $this->getNeedUserInfo();
				$sql = 'SELECT count(follow.aimId) as counts ,follow.aimId as uid,users.uname,users.fullname
						FROM `ts_follow` as follow 
						LEFT JOIN `ts_user` as users
						ON follow.aimId = users.uid
						WHERE follow.aimId IN ( ' . implode(',', $ids) . ' ) AND follow.type = \'user\'
						GROUP BY follow.aimId
						ORDER BY counts '.$order.'
						LIMIT 0,'.$limit;
				break;
			default:
				$map['active'] = 1;
				$sql = 'SELECT count(follow.aimId) as \'counts\' ,follow.aimId as uid,users.uname,users.fullname
						FROM `ts_follow` as follow 
						LEFT JOIN `ts_user` as users
						ON follow.aimId = users.uid
						WHERE follow.type = \'user\'
						GROUP BY follow.aimId
						ORDER BY counts '.$order.'
						LIMIT 0,'.$limit;

		}
		$res = M('')->query($sql);
		return $res;
	}

	private function hot($source,$order,$limit){
		$sqlQuery['order'] = 'users.userOrder '.$order;
		$sqlQuery['table'] = '`ts_blog_mention` as users';
		$sqlQuery['field'] = 'users.userOrder';
		$sqlQuery['on']    = 'users.uid';
		switch($source){
			case 'group' :
				$where  = $this->attr['group'] == 'ALL' ? '' : 'WHERE ugroup.gid = '.$this->attr['group'];
				$sql = 'SELECT distinct(ugroup.uid),'.$sqlQuery['field'].'
						   FROM `ts_user_group` as ugroup  
						   LEFT JOIN '.$sqlQuery['table'].'
						   ON ('.$sqlQuery['on'].'= ugroup.uid) 
						   '.$where.' 
						   ORDER BY '.$sqlQuery['order'].'
						   limit 0,'.$limit;
				break;
			case 'user'  :
				$ids = $this->getNeedUserInfo();
				$ids = array_unique($ids);
				$sql = 'SELECT userInfo.uid,userInfo.uname,userInfo.fullname,'.$sqlQuery['field'].'
						FROM `ts_user` as userInfo  
						LEFT JOIN '.$sqlQuery['table'].'
						ON ('.$sqlQuery['on'].' = userInfo.uid) 
						WHERE userInfo.uid IN ( ' . implode(',', $ids) . ' ) 
						ORDER BY '.$sqlQuery['order'].'
						limit 0,'.$limit;
				break;
			default:
				$sql = 'SELECT userInfo.uid,userInfo.uname,userInfo.fullname,'.$sqlQuery['field'].'
						FROM `ts_user` as userInfo  
						LEFT JOIN '.$sqlQuery['table'].'
						ON ('.$sqlQuery['on'].' = userInfo.uid) 
						WHERE userInfo.active = 1
						ORDER BY '.$sqlQuery['order'].'
						limit 0,'.$limit;
		}
		return M('')->query($sql);
	}


	private function sourceOrder($source,$order,$limit,$whereOrder){
		switch($source){
			case 'group' :
				if($this->attr['group'] !== 'ALL'){
					$map['gid'] = $this->attr['group'];
				}
				$groupUser = M('UserGroup')->where($map)->field('uid')->findAll();
				$uid = $this->_format($groupUser,'uid');
				$uid = array_unique($uid);
				$sql = 'SELECT space.credit_'.$whereOrder.',space.uid,users.uname,users.fullname
						FROM `ts_space` as space 
						LEFT JOIN `ts_user` as users
						ON space.uid = users.uid
						WHERE space.uid IN ( ' . implode(',', $uid) . ' )
						ORDER BY space.credit_'.$order.'
						LIMIT 0,'.$limit;
				break;
			case 'user'  :
				$ids = $this->getNeedUserInfo();
				$sql = 'SELECT space.credit_'.$whereOrder.',space.uid,users.uname,users.fullname
						FROM `ts_space` as space 
						LEFT JOIN `ts_user` as users
						ON space.uid = users.uid
						WHERE space.uid IN ( ' . implode(',', $ids) . ' )
						ORDER BY space.credit_'.$order.'
						LIMIT 0,'.$limit;
				break;
			default:
				$map['active'] = 1;
				$sql = 'SELECT space.credit_'.$whereOrder.',space.uid,users.uname,users.fullname
						FROM `ts_space` as space 
						LEFT JOIN `ts_user` as users
						ON space.uid = users.uid
						ORDER BY space.credit_'.$order.'
						LIMIT 0,'.$limit;
		}
		$res = M('')->query($sql);
		return $res;
	}


	private function getNeedUserInfo(){
		if(empty($this->attr['user'])) {
			$ids = explode(',', $_SESSION['mid']);
		}else {
			$umodel = M('user');
			$users  = explode(',', $this->attr['user']);
			$uname = array();

			foreach($users as $k => $v) {
				if(!is_numeric($v)) {
					$uname[] = $v;
					unset($users[$k]);
				}
			}

			if(!empty($uname)){
				$tempMap['uname'] = array('in',$uname);
				$tempUser = $umodel->where($tempMap)->field('uid')->findAll();
				foreach($tempUser as $value){
					$users[] = $value['uid'];
				}
			}

			$ids = array_unique($users);
		}
		return $ids;
	}

	/** ********************* 自定义函数 ********************* **/

	/**
	 * 根据status填充信息（3:最新动态 4:最新纪录 5:最新问题 6:最新帖子 7:最新博文 8:最新词条 9:hot值）
	 * @param3 $limit 显示的数量[默认5]
	 */
	protected function _fillByStatus($res, $status, $limit = 5) {
		$uid = $this->_format($res,'uid');
		$uid = array_filter($uid);
		$data = $this->__getDataByStatus($status,$uid,$limit);
		if(!empty($data)){
			//将数组的索引啦出来
			$tempKey = array_pop(array_keys($data));
			if(!empty($data[$tempKey])){
				$data = group($data[$tempKey],'uid');
				foreach($res as $k => $v){
					$res[$k][$tempKey] = !empty($data) && isset($data[$v['uid']]) ? array_slice($data[$v['uid']],0,$limit) : '';
				}
			}
		}
		return $res;
	}

	private function __getDataByStatus($status,$uid,$limit){
		switch($status){
			case 1:		//关注数
				$sql  = 'SELECT count(aimId) as counts,aimId as uid
					   FROM ' . C('DB_PREFIX') . 'follow
					   WHERE `aimId` IN ( ' . implode(',', $uid) . ' ) AND type = \'user\'
					   GROUP BY aimId
					   ';
				$data['followed'] = M('')->query($sql);
				break;
			
			case 3:		//最新动态
				$feed_service = service('Feed');
				$result1 = array();
				$result = array();
				foreach($uid as $value){
					$map['uid']   = $value;
					$result1 = $feed_service->get($map, $limit);
					$result = array_merge($result,$result1['data']);
				}
				$data['feed'] = $result;
				break;
			case 4:		//最新纪录
				$result = array();
				foreach($uid as $value){
					$sql = ' SELECT uid,content
							   FROM `ts_record` as table2 
							   WHERE uid = '.$value.'
							   ORDER BY cTime DESC
							   LIMIT 0,'.$limit.'
							';
					
					$tempData = M('')->query($sql);
					$result = array_merge($result,$tempData);
				}
				$data['record'] = $result;
				break;
			case 5://最新问题
				$sql = ' SELECT askId,title,uid
							   FROM `ts_ask` as table2 
							   WHERE uid in ( '.implode(',',$uid).' ) AND status = 0 AND (Select Count(*) From `ts_ask` Where uid = table2.uid And askId > table2.askId)  <'.$limit.'
							   ORDER BY cTime DESC
							';
				$data['ask'] = M('')->query($sql);
				break;
			case 6://最新帖子
				$sql = ' SELECT id,title,uid
							   FROM `ts_bbs_topic` as table2 
							   WHERE uid in ( '.implode(',',$uid).' )  AND isdel = 0 AND   (Select Count(*) From `ts_bbs_topic` Where uid = table2.uid And id > table2.id)  <'.$limit.'
							   ORDER BY cTime DESC
							';
				$data['bbs'] = M('')->query($sql);
				break;
			case 7:		//最新博文
				$sql = ' SELECT blogId,title,uid
							   FROM `ts_blog` 
							   WHERE uid in ( '.implode(',',$uid).' )  AND status IN (1,2) 
							   ORDER BY cTime DESC
						';
				$data['blog'] = M('')->query($sql);
				break;
			case 8:	//最新词条
				$sql = ' SELECT id,title,authorId as uid
							   FROM `ts_wiki` as table2 
							   WHERE authorId in ( '.implode(',',$uid).' )  AND   (Select Count(*) From `ts_wiki` Where authorId = table2.authorId And id > table2.id)  <'.$limit.'
							   ORDER BY createTime DESC
				';
				$data['wiki'] = M('')->query($sql);
				break;
			case 2: //积分经验
				$sql  = 'SELECT uid, credit_exp, credit_score
					   FROM ' . C('DB_PREFIX') . 'space 
					   WHERE `uid` IN ( ' . implode(',', $uid) . ' )';
				$data['score'] = M('')->query($sql);
				break;
			default:
				return ;
		}
		return $data;
	}

	//将二维数组格式化为一维数组
	protected function _format($arr, $field) {
		$res = array();
		foreach($arr as $v) {
			$res[] = $v[$field];
		}
		return $res;
	}
}
?>